package com.longrise.android.byjk.plugins.aboutme.personalInfo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.event.PersonalInfoEvent;
import com.longrise.android.byjk.permission.PermissionUtil;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.caculate.BitmapCaculate;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.RoundImageView;
import com.longrise.android.ui.dialog.ActionSheetDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * Created by callxkj on 2016/11/18.
 * 个人资料
 */

public class PersonalInfoActivity extends BaseActivity implements PersonalInfoContract.View, View.OnClickListener {

    private static final String TAG = "PersonalInfoActivity";

    private Toolbar mTitle;

    private RelativeLayout mRlhead;
    private RoundImageView mRihead;
    private RelativeLayout mRlnickname;
    private TextView mTvnickname;
    private RelativeLayout mRelativeUserName;
    private TextView mTvname;
    private RelativeLayout mRltruename;
    private TextView mTvtruename;
    private RelativeLayout mRlIDnumber;
    private TextView mTvIDnumber;
    private RelativeLayout mRlphomenumber;
    private TextView mTvphonenumber;
    private RelativeLayout mRlzyxx;
    private TextView mTvzyxx;
    private RelativeLayout mRlprofile;
    private TextView mTvprofile;
    private RelativeLayout mRlcpzs;
    private TextView mTvcpzs;
    private PersonalInfoContract.Presenter mPresenter;

    private View mLoading;

    private String mCurrentPage_FROM = "";
    private RelativeLayout rlwdxz;
    private TextView mTvwdxz;

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
//            mCurrentPage_FROM = state.getString(BBWebHelper.FROM_PAGE);
        } else {
            getExtraData();
        }
        return R.layout.activity_about_me;
    }

    public void initPresenter() {
        mPresenter = new PersonalPresenter(this, this);
        mPresenter.init();
    }

    private void getExtraData() {
        Intent extraIntent = getIntent();
//        mCurrentPage_FROM = extraIntent.getStringExtra(BBWebHelper.FROM_PAGE);
    }

    @Override
    public void initView() {
        mRlhead = (RelativeLayout) findViewById(R.id.about_me_top);
        mRihead = (RoundImageView) findViewById(R.id.text_selfimage);
        mRlnickname = (RelativeLayout) findViewById(R.id.base_info_nickname_rl);
        mTvnickname = (TextView) findViewById(R.id.base_info_nickname_r);
        mRelativeUserName = (RelativeLayout) findViewById(R.id.relative_username);
        mTvname = (TextView) findViewById(R.id.text_selfname);
        mRltruename = (RelativeLayout) findViewById(R.id.base_info_truename_rl);
        mTvtruename = (TextView) findViewById(R.id.base_info_truename_r);
        mRlIDnumber = (RelativeLayout) findViewById(R.id.base_info_IDnumber_rl);
        mTvIDnumber = (TextView) findViewById(R.id.base_info_IDnumber);
        mRlphomenumber = (RelativeLayout) findViewById(R.id.base_info_phomenumber_rl);
        mTvphonenumber = (TextView) findViewById(R.id.base_info_phomenumber_r);
        mRlzyxx = (RelativeLayout) findViewById(R.id.base_info_zyinfo_rl);
        mTvzyxx = (TextView) findViewById(R.id.base_info_zyinfo_r);
        mRlprofile = (RelativeLayout) findViewById(R.id.base_info_selfinfo_rl);
        mTvprofile = (TextView) findViewById(R.id.base_info_selfinfo);
//        mRlcpzs = (RelativeLayout) findViewById(R.id.base_info_cpzs_rl);
//        mTvcpzs = (TextView) findViewById(R.id.base_info_cpzs);
        mLoading = findViewById(R.id.rela_load_xqpc);
//        rlwdxz = (RelativeLayout) findViewById(R.id.base_info_wdxz_rl);
//        mTvwdxz = (TextView) findViewById(R.id.base_info_wdxz_tv);

        getExtraData();
        initTitle();
        initEvent();
        mTvzyxx.setCompoundDrawables(null, null, null, null);
        mRlzyxx.setClickable(false);
        Tracker_Google.getInstance().addGoogleScreenName("个人资料");
        initPresenter();
        EventBus.getDefault().register(this);
    }


    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.perison_infor));
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        RelativeLayout right = (RelativeLayout) mTitle.findViewById(R.id.bb_toolbar_right_rl_tv);
//        right.setVisibility(View.VISIBLE);
//        right.setOnClickListener(this);
//        TextView rightText = (TextView) mTitle.findViewById(R.id.iv_toolbar_right_tv);
//        rightText.setText(getString(R.string.yl));
    }

    private void initEvent() {
        mRlhead.setOnClickListener(this);
        mRlnickname.setOnClickListener(this);
        mRelativeUserName.setOnClickListener(this);
        mRltruename.setOnClickListener(this);
        mRlIDnumber.setOnClickListener(this);
        mRlphomenumber.setOnClickListener(this);
        mRlzyxx.setOnClickListener(this);
        mRlprofile.setOnClickListener(this);
//        mRlcpzs.setOnClickListener(this);
//        rlwdxz.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.bb_toolbar_right_rl_tv: //预览
//                mPresenter.openPersonalShow();
//                Tracker_Google.getInstance().addEvent("Mine", "preview", "预览");
//                break;

            case R.id.about_me_top: //更改头像
                getCameraPermission();
                break;

            case R.id.base_info_nickname_rl: //昵称
                mPresenter.changeNickName();
                break;

            case R.id.relative_username:
                showToast(getString(R.string.none_change_username));
                break;

            case R.id.base_info_truename_rl: //真实姓名
                mPresenter.changeTrueName(mCurrentPage_FROM);
                break;

            case R.id.base_info_IDnumber_rl: //身份证号
                mPresenter.changeIDNumber(mCurrentPage_FROM);
                break;

            case R.id.base_info_phomenumber_rl: //手机号码
                mPresenter.changePhoneNumber();
                break;

            case R.id.base_info_zyinfo_rl: //执业信息
                mPresenter.changeZYXX();
                break;

            case R.id.base_info_selfinfo_rl: //个人简介
                mPresenter.changeProfile();
                break;

//            case R.id.base_info_cpzs_rl: //产品展示
//                mPresenter.changeCPZS();
//                break;

//            case R.id.base_info_wdxz_rl: //我的勋章
//                startActivity(MyMedalActivity.class);
//                Tracker_Google.getInstance().addEvent("个人资料", "我的勋章", null);
//                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void setHeadIcon(String url, final boolean isChange) {
//        Glide.with(this).load(url)
//                .asBitmap()
//                .centerCrop()
//                .diskCacheStrategy( DiskCacheStrategy.NONE )//禁用磁盘缓存
//                .skipMemoryCache( true )//跳过内存缓存
//                .placeholder(R.drawable.default_pic)
//                .into(mRihead);
        imgeloadParams(url);
    }

    private void dismiss(String msg) {
        DZZWTools.dismissDialog(null);
        if (!TextUtils.isEmpty(msg)) {
            DZZWTools.showToast(this, msg, Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void setHeadUri(Uri uri, boolean isFrom) {
        if (uri != null) {
            Bitmap headBitmap = BitmapCaculate.decodeBitmapFromLocalPath(uri.getPath(), mRihead.getWidth(), mRihead.getHeight());
            mRihead.setImageBitmap(headBitmap);
        }
        dismiss(getString(R.string.icon_change_success));
    }

    @Override
    public void setNickName(String nickName) {
        mTvnickname.setText(nickName);
    }

    @Override
    public void setUserName(String userName) {
        mTvname.setText(userName);
    }

    @Override
    public void setTrueName(String tureName) {
        mTvtruename.setText(tureName);
    }

    @Override
    public void setIDNumber(String idNumber) {
        mTvIDnumber.setText(idNumber);
    }

    @Override
    public void setPhoneNumber(String phoneNumber) {
        mTvphonenumber.setText(phoneNumber);
    }

    @Override
    public void setZYXX(String zyxx) {
        if (TextUtils.isEmpty(zyxx)) {
            mTvzyxx.setPadding(0, 0, AppUtil.dip2px(20), 0);
            mTvzyxx.setText("无");
            mTvzyxx.setCompoundDrawables(null, null, null, null);
            mRlzyxx.setClickable(false);
        } else {
            mTvzyxx.setText(zyxx);
            Drawable drawable= getResources().getDrawable(R.drawable.by_ic_more);
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, AppUtil.dip2px(24), AppUtil.dip2px(24));
            mTvzyxx.setCompoundDrawables(null, null, drawable, null);
            mRlzyxx.setClickable(true);
        }
    }

    @Override
    public void setProfile(String profile) {
        mTvprofile.setText(profile);
    }

//    @Override
//    public void setCPZS(String cpzs) {
//        mTvcpzs.setText(cpzs);
//    }

    @Override
    public void gotoModify(String name) {
    }

    @Override
    public void showLoading(boolean isLoading) {
        mLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void startActivityForR(Intent intent, int requestCode) {
        this.startActivityForResult(intent, requestCode);
    }

    @Override
    public void startActivityForR(int requestCode, Class<?> cls) {
        Intent intent = new Intent(this, cls);
        intent.putExtra("type", requestCode);
        this.startActivityForResult(intent, requestCode);
    }

//    @Override
//    public void setMyMedal(String msg) {
//        if (TextUtils.isEmpty(msg)) {
//            mTvwdxz.setText("无");
//        } else {
//            mTvwdxz.setText(msg);
//        }
//
//    }

    @Override
    public void showToast(String msg) {
        DZZWTools.showToast(this, msg, Toast.LENGTH_SHORT);
    }

    private void getCameraPermission() {
        PermissionUtil.getInstance().requestPermission(this, PermissionUtil.Permission.CAMERA, getString(R.string.camera_permission), getString(R.string.camera_permission_hint), new PermissionUtil.PermissionCallBack() {
            @Override
            public void onSuccess() {
                changeHeadIcon();
            }

            @Override
            public void onDenied() {

            }
        });
    }

    private void changeHeadIcon() {
        new ActionSheetDialog(this).builder().setCancelable(false).setCanceledOnTouchOutside(false).addSheetItem(getString(R.string.takecamera), ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                mPresenter.toCamera(PersonalInfoActivity.this);
            }
        }).addSheetItem(getString(R.string.picture_options_selceter), ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                mPresenter.toGallery(PersonalInfoActivity.this);
            }
        }).setCancelColor(ActionSheetDialog.SheetItemColor.Black).setOnCancelListener(new ActionSheetDialog.OncancelListener() {
            @Override
            public void onCancel() {

            }
        }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void imgeloadParams(String url) {
        DisplayImageOptions option = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.default_pic).showImageOnFail(R.drawable.default_pic).cacheInMemory(false).cacheOnDisk(false).bitmapConfig(Bitmap.Config.RGB_565).build();
        ImageLoader.getInstance().displayImage(url, mRihead, option, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                super.onLoadingFailed(imageUri, view, failReason);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPersonalInfoEvent(PersonalInfoEvent event) {
        if (event.ismIsneedFinish()) {
            finish();
        }
//        if (event.ismIsUpdateMyMedal()) { //是否需要更新勋章排序
//            mPresenter.updateMyMedal();
//        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
//        outState.putString(BBWebHelper.FROM_PAGE, mCurrentPage_FROM);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.setFinished();
        EventBus.getDefault().unregister(this);
        //注意修改了昵称
        //修改headIcon
        //注意已经认证
        //setView要重新设置
    }
}
